package com.epam.ws.anatomist.example.service;

import java.util.Map;
import java.util.Properties;

import org.w3c.dom.Document;

import com.epam.ws.anatomist.example.IMessage;
import com.epam.ws.anatomist.example.RequestFactory;
import com.epam.ws.anatomist.message.MessageConverter;
import com.epam.ws.anatomist.validation.ResponseValidatorService;
import com.epam.ws.anatomist.validation.XmlAssert;

public class BaseService
{

	protected RequestFactory factory;

	protected final boolean IS_ON_FACTORY;

	public BaseService(RequestFactory factory)
	{
		this.factory = factory;
		IS_ON_FACTORY = true;
	}

	public BaseService()
	{
		IS_ON_FACTORY = false;
	}

	public void validateByControlMessage(IMessage message, String expectedMessageCfgName, Properties customData)
	{
		checkIsOnFactories();
		validateByControlMessage(MessageConverter.convertPojoToDocument(message), expectedMessageCfgName, customData);
	}

	public void validateByControlMessage(Document message, String expectedMessageCfgName, Properties customData)
	{
		checkIsOnFactories();
		Document controlMessage = factory.createControlDocument(expectedMessageCfgName, customData);
		ResponseValidatorService.validateDocumentByControlDocument(controlMessage, message);
	}

	public void validateByXpathes(IMessage message, Map<String, String> xpathes)
	{
		Document messageDocument = MessageConverter.convertPojoToDocument(message);
		XmlAssert.assertXpathEvaluatesTo(xpathes, messageDocument);
	}

	protected void checkIsOnFactories()
	{
		if (!IS_ON_FACTORY)
		{
			throw new FactoriesNotInitializedException("Trying to use factories methods without initializing");
		}
	}

	private class FactoriesNotInitializedException extends RuntimeException
	{

		private static final long serialVersionUID = -2381120937171812989L;

		public FactoriesNotInitializedException(String message)
		{
			super(message);
		}

	}

}
